﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using Kgb.Model.Models;
using System.Text;
using System.IO;

namespace KGB.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SetPlayer ()
        {
            if (Session["player"] == null)
            {
                Player player = new Player();

                var req = HttpWebRequest.Create(this.Request.UrlReferrer + "/api//players");
                req.Method = "POST";

                System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
                
                byte[] buffer = Encoding.Unicode.GetBytes(json.Serialize(player));
                req.ContentLength = buffer.Length;
                req.ContentType = "json";
                Stream postData = req.GetRequestStream();
                postData.Write(buffer, 0, buffer.Length);
                postData.Close();

                HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

                Encoding enc = System.Text.Encoding.GetEncoding(1252);
                StreamReader loResponseStream =
                new StreamReader(resp.GetResponseStream(), enc);

                string Response = loResponseStream.ReadToEnd();

                loResponseStream.Close();
                resp.Close();

                return Json(Response);
            }
            else return null;
        }
    }
}
